package _nio._socket._nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.time.LocalDateTime;

/**
 * @Author: huangya
 * @Date: 2020/5/29
 * @Description:
 */
public class NioTimeServerHandle implements Runnable {

    private Socket socket;

    public NioTimeServerHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println(111);
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            String currentTime = null;
            String body = null;
            while(true){
                body = in.readLine();
                if(body==null){
                    break;
                }
                currentTime = "query time order".equalsIgnoreCase(body)
                        ? LocalDateTime.now().toString() : "bad order";
                out.println(currentTime);
            }
        } catch (IOException e) {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
                socket=null;
            }
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                in=null;
            }
            if(out!=null){
                out.close();
                out=null;
            }
        }
    }
}
